package com.xfly.app.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.base.PermissionListener;
import com.ptmall.app.bean.LocalFile;
import com.ptmall.app.bean.LocalImageHelper;
import com.ptmall.app.bean.model.db.Account;
import com.ptmall.app.net.HttpMethods;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.net.okhttp.BusinessResponse;
import com.ptmall.app.net.okhttp.OkHttps;
import com.ptmall.app.ui.activity.LocalAlbumActivity;
import com.ptmall.app.utils.AllUtils;
import com.ptmall.app.utils.FileUtils;
import com.ptmall.app.utils.UriUtil;
import com.ptmall.app.view.AddressPickTask;
import com.ptmall.app.view.TitleBarView;
import com.xfly.app.bean.UpBean;
import com.xfly.app.bean.UserBean;
import com.xfly.app.ui.dialog.YfDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;

public class SqsjActivity extends BaseMvpActivity implements View.OnClickListener, BusinessResponse {

    TitleBarView title_bar;


    private Uri cropImageUri;
    private Uri takePicUri;
    private final int CROP_IMG_WIDTH = 700;
    private final int CROP_IMG_HEIGHT = 700;

    private final int TAKE_PICTURE = 0x000001;
    private final int TAKE_PICTURES = 0x000002;

    private List<LocalFile> checkedItems = new ArrayList<>();
    private final int MAX_IMG_COUNT = 1;

    private String[] VIDEO_PERMISSION = {
            Manifest.permission.CAMERA,
            //Manifest.permission.RECORD_AUDIO,
            //Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};


    PopupWindow popupWindow;
    private View popView;

    private ImageView sfz,zz;

    String type = "1";

    UpBean mUpBean1,mUpBean2;
    private OkHttps okHttps;
    private TextView shname,shphone,tj,ssq;
    String province_id,city_id,area_id;
    EditText gsname,address;
    ScrollView tx;
    LinearLayout shz,sjz,tg,jj;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_auth);
    }

    @Override
    public void initViews() {
        title_bar = findViewById(R.id.title_bar);
        sfz = findViewById(R.id.sfz);
        zz = findViewById(R.id.zz);
        shname = findViewById(R.id.shname);
        shphone = findViewById(R.id.shphone);
        tj = findViewById(R.id.tj);
        ssq = findViewById(R.id.ssq);
        gsname = findViewById(R.id.gsname);
        address = findViewById(R.id.address);
        tx = findViewById(R.id.tx);
        shz = findViewById(R.id.shz);
        sjz = findViewById(R.id.sjz);
        tg = findViewById(R.id.tg);
        jj = findViewById(R.id.jj);

        title_bar.setText("申请升级");
    }

    @Override
    public void initEvents() {
        okHttps = new OkHttps(this);
        okHttps.addResponseListener(this);
        title_bar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });

        sfz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                requestRuntimePermisssions(VIDEO_PERMISSION, new PermissionListener() {
                    @Override
                    public void onGranted() {//同意
                        type = "1";
                        pop();
                    }

                    @Override
                    public void onDenied(List<String> deniedList) {
                    }
                });
            }
        });
        zz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestRuntimePermisssions(VIDEO_PERMISSION, new PermissionListener() {
                    @Override
                    public void onGranted() {//同意

                        type = "2";
                        pop();
                    }

                    @Override
                    public void onDenied(List<String> deniedList) {
                    }
                });

            }
        });
        tj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mUpBean1==null&&mUpBean2==null&& TextUtils.isEmpty(province_id)&& TextUtils.isEmpty(city_id)&& TextUtils.isEmpty(area_id)&& TextUtils.isEmpty(address.getText().toString())
                        && TextUtils.isEmpty(gsname.getText().toString())){
                   showMsg("请填写详细信息");
                    return;
                }
                sj();
            }
        });
        ssq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AddressPickTask task = new AddressPickTask(getActivity());
                task.setHideProvince(false);
                task.setHideCounty(false);
                task.setCallback(new AddressPickTask.Callback() {
                    @Override
                    public void onAddressInitFailed() {
                        showMsg("数据初始化失败");
                    }

                    @Override
                    public void onAddressPicked(Province province, City city, County county) {
                        province_id = province.getAreaId();
                        city_id = city.getAreaId();
                        area_id = county.getAreaId();
                        ssq.setText(province.getAreaName()+city.getAreaName()+county.getAreaName());
                    }
                });
                task.execute("山东省", "临沂市","兰山区");
            }
        });
        getdata();
        getzt();
    }


    private void pop() {
        if (null == popupWindow) {
            if (null == popView) {
                popView = LayoutInflater.from(this).inflate(R.layout.personaldata_pop, null);
                popView.findViewById(R.id.btn1).setOnClickListener(this);
                popView.findViewById(R.id.btn2).setOnClickListener(this);
                popView.findViewById(R.id.btn_cancel).setOnClickListener(this);
            }
//            View view = LayoutInflater.from(this).inflate(R.layout.personaldata_pop, null);
            popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            popupWindow.setAnimationStyle(R.style.dialogAnim);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    AllUtils.backgroundAlpha(1.0f, getWindow());
                }
            });
            //popupWindow.showAtLocation(rootView, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn1://拍照
                takePicUri = getSomeUri();
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, takePicUri);
                startActivityForResult(openCameraIntent, TAKE_PICTURE);
                popupWindow.dismiss();
                break;
            case R.id.btn2://本地相册
                Intent intent = new Intent(getContext(),
                        LocalAlbumActivity.class);
                intent.putExtra("num", MAX_IMG_COUNT - checkedItems.size());
                startActivityForResult(intent, TAKE_PICTURES);
                popupWindow.dismiss();
                break;
            case R.id.btn_cancel:
                popupWindow.dismiss();
                break;

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PICTURE:
                if (resultCode == RESULT_OK) {
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
//                    img.setImageBitmap(bm);
                    if(type.equals("1")){
                        sfz.setImageBitmap(bm);
                    }else {
                        zz.setImageBitmap(bm);
                    }
                    setImageToView(bm);
                    checkedItems.clear();
                }
                break;
            case TAKE_PICTURES:
                checkedItems.addAll(LocalImageHelper.getInstance().getCheckedItems());
                LocalImageHelper.getInstance().getCheckedItems().clear();
                if (checkedItems.size() > 0) {
                    Bitmap bm = checkedItems.get(0).getBitmap();
                    if(type.equals("1")){
                        sfz.setImageBitmap(bm);
                    }else {
                        zz.setImageBitmap(bm);
                    }
                    setImageToView(bm);
                    checkedItems.clear();
                }
                break;
            default:
                break;
        }
    }
    /**
     * 创建任一Uri
     *
     * @return
     */
    private Uri getSomeUri() {
        String fileName = FileUtils.SDPATH + String.valueOf(System.currentTimeMillis()) + ".jpg";
        String local = FileUtils.SDPATH;
        File folder = new File(local);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        return UriUtil.getFileUri(getContext(), new File(fileName));
    }

    protected void setImageToView(Bitmap data) {

        FileUtils.saveBitmap(data, "123456");
        okHttps.postAsynFile(HttpMethods.BASE_URL + "attachment/upload", new File(FileUtils.SDPATH + "123456.JPEG"), true, 1);
    }

    @Override
    public void OnMessageResponse(int id, String jo) {
        switch (id){
            case 1:
                if(type.equals("1")){
                    mUpBean1 = okHttps.getGson().fromJson(jo, new TypeToken<UpBean>() {
                    }.getType());
                }else {
                    mUpBean2 = okHttps.getGson().fromJson(jo, new TypeToken<UpBean>() {
                    }.getType());
                }
                break;
        }
    }

    private void getdata(){
        ApiDataRepository.getInstance().myInfo(null, new ApiNetResponse<UserBean>() {
            @Override
            public void onSuccess(UserBean data) {
                shname.setText(data.getApply_name()+"");
                shphone.setText(data.getApply_phone()+"");
            }
        });
    }

    private void sj(){
        Map<String,String> map = new HashMap<>();
        map.put("idcard",mUpBean1.getId()+"");
        map.put("license",mUpBean2.getId()+"");
        map.put("company",gsname.getText().toString());
        map.put("address",address.getText().toString());
        map.put("city_id",city_id);
        map.put("province_id",province_id);
        map.put("area_id",area_id);
        ApiDataRepository.getInstance().sj(map, new ApiNetResponse<Object>(getContext()) {
            @Override
            public void onSuccess(Object data) {
                showMsg("申请成功");
                finish();
            }
        });
    }

    private void getzt(){
        ApiDataRepository.getInstance().shzt(null, new ApiNetResponse<Object>(getContext()) {
            @Override
            public void onSuccess(Object data) {
                try {
                    JSONObject jsonObject = new JSONObject(data.toString());
                    switch (jsonObject.getString("status").toString()){
                        case "0":

                            jj.setVisibility(View.GONE);
                            tg.setVisibility(View.GONE);
                            tx.setVisibility(View.VISIBLE);
                            shz.setVisibility(View.GONE);
                            sjz.setVisibility(View.GONE);
                            break;
                        case "1":

                            jj.setVisibility(View.GONE);
                            tg.setVisibility(View.GONE);
                            tx.setVisibility(View.GONE);
                            shz.setVisibility(View.VISIBLE);
                            sjz.setVisibility(View.GONE);

                            break;
                        case "2":

                            jj.setVisibility(View.GONE);
                            tg.setVisibility(View.GONE);
                            tx.setVisibility(View.GONE);
                            shz.setVisibility(View.GONE);
                            sjz.setVisibility(View.VISIBLE);
                            break;
                        case "3":
                            jj.setVisibility(View.GONE);
                            tg.setVisibility(View.VISIBLE);

                            tx.setVisibility(View.GONE);
                            shz.setVisibility(View.GONE);
                            sjz.setVisibility(View.GONE);
                            break;
                        case "4":

                            jj.setVisibility(View.GONE);
                            tg.setVisibility(View.GONE);

                            tx.setVisibility(View.VISIBLE);
                            shz.setVisibility(View.GONE);
                            sjz.setVisibility(View.GONE);
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
